import React, { PureComponent } from 'react'
import {Redirect} from 'react-router-dom'
import { Form, Input, Button, Checkbox } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import logo from '../../assets/images/logo.png'
import { setUserInfo, getUserInfo } from '../../utils/storage'
// import { reqLogin } from '../../api'
import { login } from '../../redux/actions'
import { connect } from 'react-redux'
import './index.scss'

class Login extends PureComponent {
  formRef = React.createRef();

  state = {
    isRemember: false,
  }


  componentDidMount() {
    this.loadUserInfo();
  }

  loadUserInfo() {
    // console.log(this.formRef);
    let userobj = getUserInfo();
    if (Object.keys(getUserInfo()).length !== 0) {
      if (this.formRef.current) {
        this.formRef.current.setFieldsValue({ username: userobj.username });
      }
      this.setState({
        isRemember: userobj.isRemember,
      })
    }
  }

  onFinish = (values) => {
    const { isRemember } = this.state;
    // console.log('Received values of form: ', values);
    // 请求登陆
    // const {username, password} = values

    // 调用分发异步action的函数 => 发登陆的异步请求, 有了结果后更新状态
    this.props.login(values)
    let newFormobj = { ...values, isRemember };
    setUserInfo(newFormobj);
    /* reqLogin(newFormobj).then(res => {
      // console.log('res: ', res);
      if (res.status === 0) {
        this.$message.success("登录成功");
        res.data.isRemember = isRemember;
        res.data.time = new Date().getTime();//记录何时将值存入缓存，毫秒级
        //在Admin页面处理1小时后清除LocalStorage的用户信息
        res.data.expires = 3600000;
        setUserInfo(res.data);
        this.props.history.replace("/home");
      }
    }); */
  };

  // 是否记住密码
  handleRemember = (e) => {
    // console.log('e: ', e);
    const { checked } = e.target;
    this.setState({
      isRemember: checked
    })
  }

  render() {
    // 如果用户已经登陆, 自动跳转到管理界面
    const user = this.props.user
    if (user && user._id) {
      return <Redirect to='/home' />
    }
    const { isRemember } = this.state;
    /* if(Object.keys(getUserInfo()).length!==0){
      return <Redirect to="/admin"></Redirect>
    } */
    return (
      <div className="login">
        <header className="login-header">
          <img src={logo} alt="logo" />
          <h1>React项目: 后台管理系统</h1>
        </header>
        <section className="login-content">
          <div className={user.errorMsg ? 'error-msg show' : 'error-msg'}>{user.errorMsg}</div>
          <h2>用户登陆</h2>
          <Form
            validateTrigger="onChange"
            name="normal_login"
            className="login-form"
            ref={this.formRef}
            onFinish={this.onFinish}
          >
            <Form.Item
              name="username"
              rules={[
                { required: true, whitespace: true, message: '请输入用户名' },
                { min: 4, message: '用户名至少4位' },
                { max: 12, message: '用户名至多12位' },
                { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须是英文、数字或下划线组成' },
              ]}
            >
              <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 4, message: '密码至少4位' },
                { max: 12, message: '密码至多12位' },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="密码"
              />
            </Form.Item>
            <Form.Item name="isRemember" noStyle>
              <Checkbox checked={isRemember} onChange={this.handleRemember}>记住用户名</Checkbox>
            </Form.Item>
            <Form.Item className="login-btn">
              <Button type="primary" htmlType="submit" className="login-form-button">
                登 录
              </Button>
            </Form.Item>
          </Form>
        </section>
      </div>
    )
  }
}

export default connect(
  state => ({ user: state.user }),
  { login }
)(Login)